/**
 * Author : Fengyuan(Franklin) Zhang
 * Date : 2019/3/6
 * Description : data control
 */

var request = require('request');
var Setting = require('../setting');

var DataCtrl = function () {}

module.exports = DataCtrl;

DataCtrl.refreshRecommendDXServer = function (callback) {
    var url = 'http://' + Setting.binding.ip + ':' + Setting.binding.port.toString() + '/dxserver?ac=recommend';
    request(url, function (err, respones, body) {
        if(err){
            return callback(err);
        }
        var resJson = JSON.parse(body);
        if(resJson.result == 'suc'){
            global.dxserver = resJson.data;
            return callback(null, true);
        }
        else{
            return callback(new Error('Error in getting DX server!'));
        }
    });
}

DataCtrl.postData = function (req,  callback) {
    //! post data to DX server
    if(global.dxserver){
        var url = 'http://' + global.dxserver.ds_ip + ':' + global.dxserver.ds_port.toString() + '/data';
        req.pipe(request.post(url, function (err, respones, data) {
            if(err){
                return callback(err);
            }
            var resJson = JSON.parse(data);
            if(resJson['result'] == 'err'){
                return callback(new Error(resJson['result']['message']));
            }
            var dataUrl = 'http://' + global.dxserver.ds_ip + ':' + global.dxserver.ds_port.toString() + '/data/' + resJson['data']['id'];
            return callback(null, dataUrl);
        }));
    }
}